<?php
/**
 * User: roman
 * Date: 29.06.11
 * Time: 18:33
 */

class SearchController extends Zend_Controller_Action {

    private $itemsPerPage = 10;

    public function init() {

        $this->_helper->layout()->setLayout('index-layout');

    }

    public function indexAction() {

        $tags = $this->_request->getParam('tags');

        $session = new Zend_Session_Namespace('default');

        if ($tags) {

            $session->tags = $tags;

        } else {

            $tags = $session->tags;
        }

        $connectsManager = new \Managers\Connects();

        $result = $connectsManager->search($tags);

        /**
         * Получаем тэги к итему.
         */
        foreach ($result as $key => $value) {

            $result[$key]['tags'] = $this->highlight($tags, $connectsManager->getTags($value['id']));

        }

        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Array($result));
        $paginator->setCurrentPageNumber($this->_getParam('page'));
        $paginator->setPageRange(count($result));
        $paginator->setItemCountPerPage($this->itemsPerPage);

        $this->view->items = $paginator;
    }

    private function highlight($ids, $values) {

        foreach ($values as $key => $value) {

            $style = in_array($value['id'], $ids) ? 'style="background-color: yellow"' : null;

            $values[$key]['name'] = str_replace($value['name'],
                                                     "<span $style>" . $value['name'] . ' </span > ',
                                                     $value['name']);
        }
        return $values;
    }
}
